<?php

namespace plugin\laoha\app\admin\controller;

use plugin\laoha\app\model\Cate;
use plugin\laoha\app\model\Post;
use plugin\laoha\app\validate\TitleContentValidate;
use support\Request;

class PostController extends CrudController
{	
	protected $noNeedAuth = ['groups','list','select','show','create','edit','check'];

    public function __construct()
    {
		$this->model = new Post;
		$this->validate = new TitleContentValidate;
		$this->rules = $this->getRules();
    }
	
	protected function init()
	{	
		$config = config('plugin.laoha.set.app.post',[]);
		$model = new Cate;
		$cates = laoha_query($model,['page_type'=>3,'root'=>'post','status'=>0,'order_by'=>'sort,id']);
		$cates = filter_cates($cates);
		return ['cates'=>$cates,'config'=>$config,'rules'=>$this->rules,'admin_id'=>admin_id()];
	}

    public function index()
    {
        $params = $this->init();
		return view('post/index',['params'=>$params]);
    }

	public function groups(Request $request)
	{		
		$model = new Cate;
		$cate = $model->find($request->input('id'));
		if(!empty($cate->groups)){
			return json(str2arr($cate->groups));
		}else{
			return json([]);
		}

	}

    /**
     * 列表
     * @param $request
     */
	public function list(Request $request)
	{	
		$this->set = [
			'per_page'=>10,
			'with'=>'',
			'page_type'=>1,
			'hidden'=>'content',
			'like_where'=>'title,content,pos',
		];
		$this->builder = $this->model->with(['cate:id,title,status,is_hidden','admin:id,username,nickname,avatar']);
		return parent::list($request);
	}

	public function create(Request $request)
	{
		if(!$this->canAccess('store')){
			return response('无权限');
		}
		$params = $this->init();
		return view('post/create', ['params'=>$params]);
	}

	public function edit(Request $request)
	{
		$id = $request->input('id',0);
		if(!$this->canAccess('update') || !$id){
			return response($id.'无权限');
		}
		
		$params = $this->init();
		$params['id'] = $id;
		return view('post/edit', ['params'=>$params]);
	}

}